package main

import (
	"cc/handle"
	"fmt"
	"net"
	"net/http"
	"os"
	"time"
)

var ChPool []chan string

func enableCORS(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 设置允许的源（生产环境应指定具体域名）
		w.Header().Set("Access-Control-Allow-Origin", "*")
		// 允许的请求方法
		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		// 允许的请求头
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
		// 允许携带凭证（如Cookie）
		// 注意：若设置此项，Access-Control-Allow-Origin不能为通配符*
		// w.Header().Set("Access-Control-Allow-Credentials", "true")

		// 处理预检请求
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusNoContent)
			return
		}

		next.ServeHTTP(w, r)
	})
}

func logRequest(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 获取客户端 IP（处理代理场景）
		ip, _, err := net.SplitHostPort(r.RemoteAddr)
		if err != nil {
			ip = r.RemoteAddr // 如果解析失败使用原始值
		}

		// 获取当前时间
		start := time.Now()

		// 调用下一个处理器
		next.ServeHTTP(w, r)

		// 打印日志（包含路径、IP、时间）
		fmt.Printf("[%s] %s %s %s\n",
			start.Format("2006-01-02 15:04:05"),
			ip,
			r.Method,
			r.URL.Path,
		)
	})
}

func main() {
	port := "8080"
	if len(os.Args) >= 2 {
		port = os.Args[1]
	}
	mux := http.NewServeMux()
	// 绑定路由和处理器
	mux.HandleFunc("/room/", handle.RoomHandler)
	mux.HandleFunc("/open/", handle.OpenHandler)
	mux.HandleFunc("/drop/", handle.DropHandler)
	mux.HandleFunc("/join/", handle.JoinHandler)
	mux.HandleFunc("/exit/", handle.ExitHandler)
	mux.HandleFunc("/check/", handle.CheckHandler)
	mux.HandleFunc("/ready/", handle.ReadyHandler)
	mux.HandleFunc("/select/", handle.SelectHandler)
	mux.HandleFunc("/history/", handle.HistoryHandler)
	handler := logRequest(enableCORS(mux))
	// 启动服务器，监听 8080 端口
	fmt.Println("Server started at http://localhost:" + port)
	err := http.ListenAndServe(":"+port, handler)

	// 处理启动错误
	if err != nil {
		panic(err) // 如果启动失败，直接报错退出
	}
}
